<template>
  <div class="recipient-list">
    <h2 class="page-title">Recipient Management</h2>

    <!-- Search and Filter -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="Keyword">
          <el-input
            v-model="searchForm.keyword"
            placeholder="Search name/email/phone"
            clearable
            @clear="handleSearch"
            style="width: 260px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            Search
          </el-button>
          <el-button @click="handleReset">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Action Bar -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>Recipient List</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            Add Recipient
          </el-button>
        </div>
      </template>

      <!-- Table -->
      <el-table
        v-loading="loading"
        :data="recipientList"
        style="width: 100%"
      >
        <el-table-column prop="recipient_id" label="ID" width="60" />
        <el-table-column prop="full_name" label="Full Name" width="120" />
        <el-table-column prop="date_of_birth" label="Date of Birth" width="120">
          <template #default="{ row }">
            {{ formatDate(row.date_of_birth) }}
          </template>
        </el-table-column>
        <el-table-column prop="contact_email" label="Email" width="200" show-overflow-tooltip />
        <el-table-column prop="contact_phone" label="Phone" width="140" />
        <el-table-column prop="address" label="Address" width="180" show-overflow-tooltip />
        <el-table-column prop="registration_date" label="Registration Date" width="160">
          <template #default="{ row }">
            {{ formatDate(row.registration_date) }}
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="230">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              Edit
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              :disabled="!row.can_delete"
              :title="!row.can_delete ? 'This recipient has order records and cannot be deleted' : ''"
            >
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="Full Name" prop="full_name">
          <el-input v-model="formData.full_name" placeholder="Enter full name" />
        </el-form-item>
        <el-form-item label="Date of Birth" prop="date_of_birth">
          <el-date-picker
            v-model="formData.date_of_birth"
            type="date"
            placeholder="Select date"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="Contact Email" prop="contact_email">
          <el-input v-model="formData.contact_email" placeholder="Enter email" />
        </el-form-item>
        <el-form-item label="Contact Phone" prop="phone_number" required>
          <el-input v-model="formData.phone_number" placeholder="Enter phone number">
            <template #prepend>
              <el-select v-model="formData.country_code" placeholder="+86" style="width: 100px">
                <el-option label="+86 China" value="+86" />
                <el-option label="+1 USA" value="+1" />
                <el-option label="+44 UK" value="+44" />
                <el-option label="+81 Japan" value="+81" />
                <el-option label="+82 Korea" value="+82" />
                <el-option label="+65 Singapore" value="+65" />
                <el-option label="+852 Hong Kong" value="+852" />
                <el-option label="+853 Macau" value="+853" />
                <el-option label="+886 Taiwan" value="+886" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="Address" prop="address">
          <el-input v-model="formData.address" type="textarea" :rows="3" placeholder="Enter address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSubmit">Confirm</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { recipientAPI } from '@/api'

// Search form
const searchForm = reactive({
  keyword: ''
})

// Pagination
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// Data list
const recipientList = ref([])
const loading = ref(false)

// Dialog
const dialogVisible = ref(false)
const dialogTitle = ref('Add Recipient')
const formRef = ref(null)
const formData = reactive({
  recipient_id: null,
  full_name: '',
  date_of_birth: '',
  contact_email: '',
  contact_phone: '',
  country_code: '+86',
  phone_number: '',
  address: ''
})

// Form validation rules
const formRules = {
  full_name: [{ required: true, message: 'Please enter full name', trigger: 'blur' }],
  date_of_birth: [{ required: true, message: 'Please select date of birth', trigger: 'change' }],
  contact_email: [
    { required: true, message: 'Please enter email', trigger: 'blur' },
    { type: 'email', message: 'Please enter valid email format', trigger: 'blur' }
  ],
  phone_number: [
    { required: true, message: 'Please enter phone number', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('Please enter phone number'))
        } else if (!/^\d+$/.test(value)) {
          callback(new Error('Phone number can only contain digits'))
        } else if (value.length < 7) {
          callback(new Error('Phone number must be at least 7 digits'))
        } else if (value.length > 15) {
          callback(new Error('Phone number cannot exceed 15 digits'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// Load list data
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const data = await recipientAPI.getList(params)
    recipientList.value = data.data || []
    pagination.total = data.count || 0
  } catch (error) {
    ElMessage.error('Failed to load data')
  } finally {
    loading.value = false
  }
}

// Search (reset to page 1)
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// Page change (do not reset page number)
const handlePageChange = () => {
  loadData()
}

// Reset
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: ''
  })
  handleSearch()
}

// Add
const handleAdd = () => {
  dialogTitle.value = 'Add Recipient'
  Object.assign(formData, {
    recipient_id: null,
    full_name: '',
    date_of_birth: '',
    contact_email: '',
    contact_phone: '',
    country_code: '+86',
    phone_number: '',
    address: ''
  })
  dialogVisible.value = true
}

// Edit
const handleEdit = (row) => {
  dialogTitle.value = 'Edit Recipient'
  Object.assign(formData, row)
  // Split phone number
  const { country_code, phone_number } = splitPhone(row.contact_phone)
  formData.country_code = country_code
  formData.phone_number = phone_number
  dialogVisible.value = true
}

// Delete
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete recipient ${row.full_name}?`,
      'Warning',
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    await recipientAPI.delete(row.recipient_id)
    ElMessage.success('Deleted successfully')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete')
    }
  }
}

// Split phone number: extract country code and number from full phone
const splitPhone = (fullPhone) => {
  if (!fullPhone) return { country_code: '+86', phone_number: '' }
  
  // List of supported country codes (sorted by length from long to short to avoid matching errors)
  const countryCodes = ['+886', '+853', '+852', '+86', '+82', '+81', '+65', '+44', '+1']
  
  for (const code of countryCodes) {
    if (fullPhone.startsWith(code)) {
      return {
        country_code: code,
        phone_number: fullPhone.substring(code.length)
      }
    }
  }
  
  // If no known country code matched, default to +86
  return { country_code: '+86', phone_number: fullPhone.replace(/^\+/, '') }
}

// Merge phone number: country code + number
const mergePhone = () => {
  return formData.country_code + formData.phone_number.trim()
}

// Submit form
const handleSubmit = async () => {
  await formRef.value.validate()
  try {
    // Merge phone number
    const submitData = { ...formData }
    submitData.contact_phone = mergePhone()
    delete submitData.country_code
    delete submitData.phone_number
    
    if (formData.recipient_id) {
      await recipientAPI.update(formData.recipient_id, submitData)
      ElMessage.success('Updated successfully')
    } else {
      await recipientAPI.create(submitData)
      ElMessage.success('Created successfully')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('Operation failed')
  }
}

// Format date
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('en-US')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.recipient-list {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
